_IG_Analytics("UA-1487682-1", "/svn");
var debug = false;
var prefs = new _IG_Prefs(__MODULE_ID__);
var state = "unknown";
var station = "unknown"
var latitude = 0.0;
var longitude = 0.0;
var isNearCapital = false;
var cachedLocation = '';
var cachedForecast = '';
var cachedWarning = '';
var cachedToday = '';

// These regexes may be overridden as required
// today/tomorrow forecasts (more verbose, at start of page)
todayRegex = /\w*?forecast for (\w+day.*?)\s*XiX(.*?)\.?\s*Precis.\s*(.+?)[\.\s]*XiX(\s*XiX|.+?(max.\s*\d+).*?XiX)/ig;
// extended day forecasts, further down page
dayRegex = /XiX([^X]\w+?day)\s*(.+?)[\.\s]*min.?\s+(\d+)\s*(?:XiX|)\s*max.?\s+(\d+)/ig;
// current temp/time/etc.
currentlyRegex = /href=.(.{10,60}?shtml).>([a-zA-Z\.,\- ]+?)<\/a><\/td>\s*XiX\s*<td>.+?(\d+:\d+[ap]m).+?XiX\s*<td>([\d\.]+).+?XiX.+?XiX.+?XiX.+?<td>(\d+)/ig;
currentlyRegexOuter = /href=.(.{10,60}?shtml).>([a-zA-Z\.,\- ]+?)<\/a><\/td>\s*XiX\s*<td>(.+?)<\/td>\s*XiX\s*<\/tr>/ig;



// current warnings
warningRegex = /warning summary.*?XiX\s*(.*?)\s*XiX\s*(?:Forecast|Updated\s*Forecast|Current\s*Weather\s*Situation)/ig;

function getIcon(fc) {
    if (typeof(imageCounter) == "undefined")
        imageCounter = 0;
    imageCounter += 1;
    // return am <img> string best describing the forecast
            var prefix = '<img height="32" weight="32" align="left" src="';
    var suffix = '"/>';
    var fine = _IG_GetImageUrl('http://bomweathergadget.googlecode.com/svn/trunk/images/fine.gif');
    var fewShowers = _IG_GetImageUrl('http://bomweathergadget.googlecode.com/svn/trunk/images/few_showers.gif');
    var showers = _IG_GetImageUrl('http://bomweathergadget.googlecode.com/svn/trunk/images/showers.gif');
    var unknown = _IG_GetImageUrl('http://bomweathergadget.googlecode.com/svn/trunk/images/question.gif');
    var mostlyCloudy = _IG_GetImageUrl('http://bomweathergadget.googlecode.com/svn/trunk/images/mostly_cloudy.gif');
    var mostlyFine = _IG_GetImageUrl('http://bomweathergadget.googlecode.com/svn/trunk/images/mostly_fine.gif');
    var thunderstorm = _IG_GetImageUrl('http://bomweathergadget.googlecode.com/svn/trunk/images/thunderstorm.gif');

    if (/^fine$/i.test(fc)) return prefix + fine + suffix;
    if (/(thunder|hail|lightning|storm)/i.test(fc)) return prefix + thunderstorm + suffix;
    if (/(light|scattered|occassional|chance).+(shower|drizzle)/i.test(fc)) return prefix + fewShowers + suffix;
    if (/showers?\s*clearing/i.test(fc)) return prefix + fewShowers + suffix;
    if (/(rain|shower|drizzle)/i.test(fc)) return prefix + showers + suffix;
    if (/(mostly|mainly)\s+(fine|sunny)/i.test(fc)) return prefix + mostlyFine + suffix;
    if (/cloud/i.test(fc)) return prefix + mostlyCloudy + suffix;
    if (/(fine|dry)/i.test(fc)) return prefix + fine + suffix;
    return prefix + unknown + suffix;
}
function processToday(txt) {
    if (prefs.getBool("showCurrentTemp")) {
            var myDelimiter = "XiX";
            var oneLiner = txt.replace(/\n/g, myDelimiter).replace(/\r/g, '');
            _gel("currently_span").innerHTML = "processing";
            var content_html = "??? - " + prefs.getString("station");

            while ((result = currentlyRegexOuter.exec(oneLiner)) != null) {
                // arg 1 is URL, arg 2 location, arg 3 all other

                _gel("currently_span").innerHTML = result[0];

                wparms = result[3].split(/\s*<\/td>\s*XiX\s*<td>\s*/);
                // 0: date

                if (result[2] == station) {
                    if (prefs.getBool("showLocationAndTime"))
                        content_html = '<a href="http://www.bom.gov.au/' + result[1] + '" target="_blank">' + result[2] + " at " + (/\/(.+)/.exec(wparms[0]))[1] + "</a> : " + wparms[1] + "&deg;";
                    else
                        content_html = '<a href="http://www.bom.gov.au/' + result[1] + '" target="_blank">'  + wparms[1] + "&deg;</a>";
                    if (prefs.getBool('showHumidity')) content_html += ', ' + wparms[4] + '%';
                    if (prefs.getBool('showRainfall')) content_html += ', ' + wparms[12] + 'mm';
                    if (prefs.getBool('showWind')) content_html += ', ' + wparms[7] + 'km/h&nbsp;(' + wparms[6] + ')';
                    if (prefs.getBool('showPressure')) content_html += ', ' + wparms[11] + 'hPa';
                }
            };

            cachedToday = content_html;
    } else {
            cachedToday = '';
        
    }
    
    showToday();
}


function processForecast(txt) {
    var myDelimiter = "XiX";
    var oneLiner = txt.replace(/\n/g, myDelimiter).replace(/\r/g, '').replace(/<.+?>/g, '');
    _gel("forecast_div").innerHTML = "Processing forecast...";
    var content_html = '';
    var warning_html = '';
    var daysRemaining = 0 + prefs.getString("daysToShow");
    if (debug) {
            content_html += getIcon('thunderstorms') + 'thunderstorms<BR clear="ALL">';
            content_html += getIcon('showers') + 'showers<BR clear="ALL">';
            content_html += getIcon('showers clearing') + 'showers clearing<BR clear="ALL">';
            content_html += getIcon('rain') + 'rain<BR clear="ALL">';
            content_html += getIcon('hail') + 'hail<BR clear="ALL">';
            content_html += getIcon('mostly fine') + 'mostly fine<BR clear="ALL">';
    }
    if (isNearCapital) {
            var lastMatchedIndex = 0;
            while ((result = todayRegex.exec(oneLiner)) != null) {
                lastMatchedIndex = todayRegex.lastIndex;
                daysRemaining-=1;
                if (daysRemaining >= 0)  {
                    verbose = result[2].replace(/XiX/g, "\n");
                    precis = result[3].replace(/XiX/g, "\n");
                    if (result[5] == null) result[5] = '';
                    else result[5] = ", " + result[5].toLowerCase();
                    if (prefs.getBool("showIcons"))
                        content_html += getIcon(precis);
                    content_html += '<B><a href="' + urlForecast[state] + '" target="_blank">' + result[1] + "</a></B>: " + (prefs.getBool('showPrecis')?precis:verbose) + result[5] + '<BR clear="ALL">';
                }
            };

            // Make sure we don't match the already-processed days with this regex
            dayRegex.lastIndex = lastMatchedIndex;
            while ((result = dayRegex.exec(oneLiner)) != null) {
                daysRemaining-=1;
                if (daysRemaining >= 0)  {
                        if (prefs.getBool("showIcons"))
                            content_html += getIcon(result[2]);
                            content_html += "<B>" + result[1].replace(/XiX/g, "") + "</B>: " + result[2] + ", " + result[3] + "&nbsp;-&nbsp;" +  result[4] + '<BR clear="ALL">';
                        //content_html += result[0] + "<P>";
                }
            }

            isNilRegex = /^nil/ig;
            if (prefs.getBool("showWarnings")) 
                    while ((result = warningRegex.exec(oneLiner)) != null) {
                        w = result[1].replace(/XiX/g,"\n");
                        if (! isNilRegex.test(w))
                                warning_html += '<P><a href="' + urlForecast[state] + '" target="_blank">' + w + "</a></P>";
                    }

    } else {
        content_html = "(forecasts are currently only available near capital cities!!!)";
    }
    cachedForecast = content_html;
    cachedWarning = warning_html;

    showForecast();
}

function showForecast() {
    _gel("forecast_div").innerHTML = cachedForecast;
    _gel("warning_div").innerHTML = cachedWarning;
    _IG_AdjustIFrameHeight();
}

function showToday() {
    _gel("currently_span").innerHTML = cachedToday;
    _IG_AdjustIFrameHeight();
}

function fetchForecast () {
    urlForecast = new Object();
    if (isNearCapital) {
            urlForecast["ACT"] = "http://www.bom.gov.au/products/IDN10035.shtml";
            urlForecast["Vic"] = "http://www.bom.gov.au/products/IDV10450.shtml";
            urlForecast["NSW"] = "http://www.bom.gov.au/products/IDN10064.shtml";
            urlForecast["NT"] = "http://www.bom.gov.au/products/IDD10150.shtml";
            urlForecast["Qld"] = "http://www.bom.gov.au/products/IDQ10095.shtml";
            urlForecast["SA"] = "http://www.bom.gov.au/products/IDS10034.shtml";
            urlForecast["Tas"] = "http://www.bom.gov.au/products/IDT65061.shtml";
            urlForecast["WA"] = "http://www.bom.gov.au/products/IDW12300.shtml";
    } else {
            dayRegex = /sdflkjdsf/; // never match
            urlForecast["Vic"] = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDV10580.txt";
            urlForecast["NSW"] = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDN10084.txt";
            urlForecast["NT"] = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDD10110.html";
            urlForecast["Qld"] = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDQ10600.txt";
            urlForecast["SA"] = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDS10043.txt";
            urlForecast["Tas"] = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDT16700.html";
            urlForecast["WA"] = "http://www.bom.gov.au/cgi-bin/wrap_fwo.pl?IDW14500.txt";
    }
    forecastURL = urlForecast[state];
    if (state == "Vic") 
    {
        fetchXMLForecast()
        return;
    }
    if (! isNearCapital) {
        content_html = "(forecasts are currently only available near capital cities)";
        cachedForecast =content_html;
        cachedWarning='';
        showForecast();
        return;
    }
    _gel("forecast_div").innerHTML = "Preparing to fetch the forecast..";
    if (state == "NSW") {
        todayRegex =  /\w*?forecast for (\w+day.*?)\s*XiX(.*?)\.?\s*Precis.\s*(.+?)[\.\s]*XiX(.*?city.+?(max.\s*\d+)|.+?XiX\s*?XiX)/ig;
        dayRegex = /XiX\s*(\w+?day)\s*(?:XiX|)(.+?)XiX.*?city.+?min.\s*?(\d+)\s*max.\s*?(\d+)/ig;
    }

    _gel("forecast_div").innerHTML = "Retrieving forecast...";
    _IG_FetchContent(forecastURL, processForecast);
}

function fetchXMLForecast() {
        // Support the new precis format the BOM is using in Victoria from late October 08
        var regionID = new Object();
        regionID["Aireys Inlet"] ="PT001";
        regionID["Albury"] ="PT084";
        regionID["Ararat"] ="PT002";
        regionID["Avalon"] ="PT003";
        regionID["Bairnsdale"] ="PT004";
        regionID["Ballarat"] ="PT005";
        regionID["Beechworth"] ="PT006";
        regionID["Benalla"] ="PT007";
        regionID["Bendigo"] ="PT008";
        regionID["Cape Nelson"] ="PT009";
        regionID["Cape Otway"] ="PT010";
        regionID["Casterton"] ="PT011";
        regionID["Castlemaine"] ="PT012";
        regionID["Colac"] ="PT014";
        regionID["Combienbar"] ="PT015";
        regionID["Corryong"] ="PT016";
        regionID["Cranbourne"] ="PT017";
        regionID["Dartmouth"] ="PT018";
        regionID["Echuca"] ="PT019";
        regionID["Edi Upper"] ="PT020";
        regionID["Falls Creek"] ="PT022";
        regionID["Frankston"] ="PT023";
        regionID["Gabo Island"] ="PT024";
        regionID["Geelong"] ="PT025";
        regionID["Gelantipy"] ="PT026";
        regionID["Hamilton"] ="PT027";
        regionID["Hastings"] ="PT013";
        regionID["Heywood"] ="PT028";
        regionID["Horsham"] ="PT029";
        regionID["Kerang"] ="PT031";
        regionID["Kilmore Gap"] ="PT032";
        regionID["Kyabram"] ="PT033";
        regionID["Lake Eildon"] ="PT034";
        regionID["Lakes Entrance"] ="PT035";
        regionID["Latrobe Valley"] ="PT036";
        regionID["Laverton"] ="PT037";
        regionID["Longerenong"] ="PT038";
        regionID["Mallacoota"] ="PT040";
        regionID["Maryborough"] ="PT041";
        regionID["Melbourne"] ="PT042";
        regionID["Mildura"] ="PT043";
        regionID["Moorabbin"] ="PT044";
        regionID["Mortlake"] ="PT045";
        regionID["Mount Buller"] ="PT046";
        regionID["Mount Dandenong"] ="PT047";
        regionID["Mount Hotham"] ="PT048";
        regionID["Mount Moornapa"] ="PT049";
        regionID["Mount Nowa Nowa"] ="PT050";
        regionID["Nhill"] ="PT051";
        regionID["Noojee"] ="PT052";
        regionID["Omeo"] ="PT053";
        regionID["Orbost"] ="PT054";
        regionID["Ouyen"] ="PT055";
        regionID["Phillip Island"] ="PT056";
        regionID["Point Hicks"] ="PT057";
        regionID["Point Wilson"] ="PT058";
        regionID["Port Fairy"] ="PT059";
        regionID["Portland"] ="PT060";
        regionID["Redesdale"] ="PT061";
        regionID["Rhyll"] ="PT062";
        regionID["Rutherglen"] ="PT063";
        regionID["Sale"] ="PT064";
        regionID["Scoresby"] ="PT065";
        regionID["Seymour"] ="PT066";
        regionID["Sheoaks"] ="PT067";
        regionID["Shepparton"] ="PT068";
        regionID["Strathbogie"] ="PT070";
        regionID["Swan Hill"] ="PT071";
        regionID["Tatura"] ="PT072";
        regionID["Tullamarine"] ="PT073";
        regionID["Walpeup"] ="PT074";
        regionID["Wangaratta"] ="PT075";
        regionID["Warracknabeal"] ="PT076";
        regionID["Warrnambool"] ="PT077";
        regionID["Watsonia"] ="PT078";
        regionID["Weeaproinah"] ="PT079";
        regionID["Wilsons Promontory"] ="PT080";
        regionID["Wonthaggi"] ="PT081";
        regionID["Yarra Glen"] ="PT082";
        regionID["Yarrawonga"] ="PT083";

                var url = "http://www.bom.gov.au/fwo/IDV10753/IDV10753." + regionID[station] + ".xml"
                _gel("forecast_div").innerHTML = "Fetching XML forecast...";
                _IG_FetchContent(url, processXMLForecast);
        };
               
function loadXml(response) { var doc; if (window.ActiveXObject) { doc = new ActiveXObject("Microsoft.XMLDOM"); doc.async = "false"; doc.loadXML(response); } else { var parser = new DOMParser(); doc = parser.parseFromString(response, "text/xml"); } return doc; } 

function getImageURL(val)
{
        var imId='id'+ val;
        var images='';
        if (prefs.getBool("useBomIcons")) {
                images = {id0:'blank.png', id1:'sunny.png', id2:'clear.png', id3:'partly-cloudy.png',id4:'cloudy.png', id6:'haze.png', id8:'light-rain.png', id9:'wind.png', id10:'fog.png', id11:'showers.png', id12:'rain.png', id13:'dust.png', id14:'frost.png', id15:'snow.png', id16:'storm.png', id17:'light-showers.png'};
                if(!images[imId]) {return false;}
                else
                {
                        var img = images[imId];
                        var imgPath='http://www.bom.gov.au/weather-services/images/symbols/large/';
                        var imgTag= _IG_GetImageUrl(imgPath + img);
                        return imgTag;
                }
        } else {
                images = {id0:'question.gif', id1:'fine.gif', id2:'fine.gif', id3:'mostly_cloudy.gif',id4:'mostly_cloudy.gif', id6:'haze.gif', id8:'few_showers.gif', id9:'wind.gif', id10:'fog.gif', id11:'showers.gif', id12:'showers.gif', id13:'dust.gif', id14:'frost.gif', id15:'snow.gif', id16:'thunderstorm.gif', id17:'few_showers.gif'};
                var img = images[imId];
                var imgPath='http://bomweathergadget.googlecode.com/svn/trunk/images/';
                var imgTag= _IG_GetImageUrl(imgPath + img);
                return imgTag;
        }
}

function processXMLForecast (response) {
            var responseXML = loadXml(response); 
            if (responseXML == null || typeof(responseXML) != "object" || 
                    responseXML.firstChild == null) {
                    _gel("forecast_div").innerHTML = "<i>Invalid data.</i><p>" + url + "</p>";
                    return;
            }

            _gel("forecast_div").innerHTML = "Processing XML forecast...";
            var details = new Object(); // map state name to BOM URL for more detailed forecast

            var content_html = '';
            var warning_html = '';
            var forecastList = responseXML.getElementsByTagName("forecast-period");
            var dayNames = {0: 'Fri', 1: 'Sat', 2: 'Sun', 3: 'Mon', 4: 'Tue', 5: 'Wed', 6: 'Thu'};
            var daysRemaining = 0 + prefs.getString("daysToShow");
            for (var i = 0; i < forecastList.length; i++) {
                var forecastNode = forecastList.item(i);
                if (0 + forecastNode.getAttribute("index") > daysRemaining) continue;
                var startUTC = forecastNode.getAttribute("start-time-local");
                var startDate = new Date();
                var currentDate = new Date();
                startDate.setTime(Date.UTC(startUTC.substr(0,4), startUTC.substr(5,2), startUTC.substr(8,2)));
                var dayOfWeek = 'unknown';
                if (startDate.getDate() == currentDate.getDate()) {
                        dayOfWeek = 'Today';
                } else {
                        dayOfWeek = dayNames[startDate.getDay()];
                }
                var elementList = forecastNode.childNodes;
                var forecastObject = new Object();
                for (var j = 0; j < elementList.length; j++) {
                        var elementNode = elementList.item(j);
                        if (elementNode.nodeName == "element" || elementNode.nodeName == "text") {
                                var elementType = elementNode.getAttribute("type");
                                forecastObject[elementType] = elementNode.firstChild.nodeValue;
                        }
                }
                if (prefs.getBool("showIcons") && forecastObject["forecast_icon_code"])
                        content_html += '<img src="' + getImageURL(forecastObject["forecast_icon_code"]) + '" align="left"/>';
                        content_html += '<b><a href="' + forecastURL + '" target="_blank">' + dayOfWeek + "</a></b>";
                if (forecastObject["air_temperature_maximum"]) 
                        if (forecastObject["air_temperature_minimum"]) content_html += ': ' + forecastObject["air_temperature_minimum"] + "-" + forecastObject["air_temperature_maximum"];
                        else content_html += ':' + forecastObject["air_temperature_maximum"];
                content_html += "<br>";
                if (forecastObject["precis"]) content_html += ' <i>' + forecastObject["precis"] + '</i>';

                content_html += '<br clear="ALL">';
            }
            cachedForecast = content_html;
            cachedWarning = warning_html;
            showForecast();
};


function fetchToday () {
    _gel("currently_span").innerHTML = "preparing";
    urlNow = new Object();
    urlNow["Vic"] = "http://www.bom.gov.au/products/IDV60800.shtml";
    urlNow["NSW"] = "http://www.bom.gov.au/products/IDN60800.shtml";
    urlNow["NT"] = "http://www.bom.gov.au/products/IDD60800.shtml";
    urlNow["Qld"] = "http://www.bom.gov.au/products/IDQ60800.shtml";
    urlNow["WA"] = "http://www.bom.gov.au/products/IDW60800.shtml";
    urlNow["SA"] = "http://www.bom.gov.au/products/IDS60800.shtml";
    urlNow["ACT"] = "http://www.bom.gov.au/products/IDN60902.shtml";
    urlNow["Tas"] = "http://www.bom.gov.au/products/IDT60800.shtml";
    url = urlNow[state];

    _gel("currently_span").innerHTML = "retrieving";
    _IG_FetchContent(url, processToday, { refreshInterval: 300 });
}

function showRadar() {
    if (longitude == 0.0) {
        _gel("radar_img").alt = "Coordinates unknown; not showing radar.";
        var radarURL = "http://ows.bom.gov.au/cgi-bin/mapserver/users/bomw0473/latest?layers=free_elevation,RadarSA,RadarVIC,RadarNSW,RadarNT,RadarWA,RadarTAS,RadarQLD,free_locationradar&bbox=103.459464,-53.778035,160.605535,3.368035&version=1.1.1&service=WMS&request=getMap&height=310&width=310";
    } else {
        var radius = 0.75;
        var radarURL = "http://ows.bom.gov.au/cgi-bin/mapserver/users/bomw0473/latest?layers=free_elevation,RadarSA,RadarVIC,RadarNSW,RadarNT,RadarWA,RadarTAS,RadarQLD,free_locationradar&bbox=" + (longitude - radius) + "," + (latitude - radius) + "," + (radius + longitude) + "," + (radius + latitude) + "&version=1.1.1&service=WMS&request=getMap&height=310&width=310";
        _gel("radar_img").src = radarURL;
    }
}

function showContent () {
    fetchForecast();
    fetchToday();
    //if (prefs.getBool("showRadar")) showRadar();
}

function startup() {
    loc = prefs.getString("location").split("|");
    state = loc[0];
    station = loc[1];
    _IG_SetTitle("Weather for " + loc[1]);
    isNearCapital = (loc[2] == 1);
    if (debug) {
        document.writeln("state is " + state);
        document.writeln("station is " + station);
    };
    longitude = Number(loc[3]);
    latitude = Number(loc[4]);

    prefs.set("station", station);

    if (debug) prefs.dump();
    showContent();
}
_IG_RegisterOnloadHandler(startup);
